package crawler.web.engine.config;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import library.utils.file.FileUtils;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * @author waynechen May 23, 2012 9:13:01 PM
 */
public class ConfigGenerator {
	private static DocumentBuilder document;
	static {
		try {
			document = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		System.out.println("package crawler.web.engine.config;");
		System.out.println("/**");
		System.out.println("* 这个文件中包含spring的bean名称, 方便引用, 减少编码出错率<br>");
		System.out.println("* 不要修改这个类, 这个类是由spring的配置文件生成的<br>");
		System.out.println("*/");
		System.out.println("public class SpBN {");
		StringBuilder sb = new StringBuilder();
		try {
			for (Document dom : getDoms()) {
				NodeList nodes = dom.getElementsByTagName("bean");
				for (int i = 0; i < nodes.getLength(); i++) {
					try {
						sb.setLength(0);
						Node item = nodes.item(i);
						NamedNodeMap attrs = item.getAttributes();
						//輸出文檔註釋
						sb.append("/**").append("\n");
						NodeList childNodes = item.getChildNodes();
						for (int j = 0; j < childNodes.getLength(); j++) {
							if (childNodes.item(j).getNodeName().equals("beans:description")) {
								sb.append("*" + childNodes.item(j).getTextContent() + "<br>").append("\n");
								sb.append("* 类型为: " + attrs.getNamedItem("class").getNodeValue() + "<br>").append("\n");
							}
						}
						sb.append("*/").append("\n");
						//輸出成員變量
						sb.append("public static final String ");
						String id = attrs.getNamedItem("id").getNodeValue();
						sb.append(id);
						sb.append(" = \"" + id + "\";").append("\n");

						//換行
						sb.append("\n");
					} catch (Exception e) {
						continue;
					}
					System.out.println(sb);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("}");
	}

	private static Document[] getDoms() throws SAXException, IOException {
		String file = ConfigGenerator.class.getClassLoader().getResource("applicationContext.xml").getFile();
		File dir = new File(file).getParentFile();
		File[] files = FileUtils.getFiles(dir, "applicationContext.*xml");
		Document[] doms = new Document[files.length];
		for (int i = 0; i < doms.length; i++)
			doms[i] = document.parse(files[i].getAbsolutePath());
		return doms;
	}

}

//
//
//
//
//
//
//
//
//
//
//
//
